<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" class="table-view">
      <template #form="{ form }">
        <!-- {{ form }} -->
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" v-if="formShow" class="form-view">
          <template #ShopCascade>
            <SelectsShopCascade v-model:platform="form.platform_id" v-model:site="form.site_id" v-model:shop="form.shop_id" />
          </template>
          <template #storehouse="{ item }">
            <WarehouseSelect style="width: 180px" v-model:modelValue="form[item.field].value" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <div class="w-[100%]">
          <div class="my-[10px] mb w-[100%]">
            <el-tabs v-model="statusRadio" class="demo-tabs" @tab-click="handleStatusChange">
              <el-tab-pane label=" 全部" name="">
                <template #label>
                  全部<span class="text-[#999]" v-if="tab.length">({{ getTotal() }})</span>
                </template>
              </el-tab-pane>
              <el-tab-pane v-for="item in tab" :key="item.exchange_status" :label="item.label" :name="item.exchange_status">
                <template #label>
                  {{ item.exchange_status_desc }}<span class="text-[#999]">({{ item.quantity }})</span>
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="flex">
            <!-- <div class="affix-btn py-[8px] pt-[0]"> -->
            <el-button type="primary" @click="handleEdit('add')" v-hasPermi="[userAuthList.return.add]">
              <span class="dk-iconfont icon-Plus"></span>
              新增退换货
            </el-button>
            <el-button type="primary" @click="handleBatchApproval" v-hasPermi="[userAuthList.return.batchAudit]" style="margin-left: 8px">批量审核</el-button>
            <!-- </div> -->

            <div class="ml-[auto]">
              <el-dropdown v-hasPermi="[userAuthList.return.export]">
                <el-button> 导出 <span class="dk-iconfont icon-Download"></span> </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="importHandleClick(1)">导出退换货SKU明细</el-dropdown-item>
                    <el-dropdown-item @click="importHandleClick(2)">导出退换货订单明细</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </template>

      <template #GoodsSlot="{ row }">
        <ExpandList :show-expand="row?.products?.length > 1" :expand="row.expandStatus" @change="rendererView" :length="row?.products?.length">
          <template #default="{ expand }">
            <div class="product-item" v-for="(item, index) in getRows(row, expand)" :key="`${item.sku}${index}`">
              <div class="border-[var(--base-border-color)] border-[1px] rounded-[4px] p-[7px] text-[14px] text-[#3A4259] relative leading-[22px] w-[378px]">
                <div class="flex items-center">
                  <!-- <span class="text-[#3487ff] text-[14px]">{{ item.sku }}</span> -->

                  <div class="w-[180px] flex-1">
                    <VText :value="item.sku" :line="1" type="link" :copy="true" />
                  </div>
                  <el-divider direction="vertical" />
                  <VText title="退货数量" :value="item.quantity" :line="1" />
                </div>
                <VText :value="item.sku_cn_title" :line="1" />
                <VText title="自定义SKU" :value="item.custom_sku" :line="1" :copy="true" />

                <div class="text-red">
                  <VText title="退货原因" :value="item.problem_type_desc + (item.problem_description ? `（${item.problem_description}）` : '')" :line="1" />
                </div>
                <div class="absolute right-[0] top-[0]">
                  <span class="leading-[17px]"> {{ row.original_order_currency }} {{ item.original_price }} </span>
                  <span class="bg-[#EBECEE] text-[#FF0000] rounded-bl-[4px] px-[4px] ml-[4px]"> *{{ item.quantity }} </span>
                </div>
              </div>
            </div>
          </template>
        </ExpandList>
      </template>

      <!-- <div>
          {row.products.map(n => (
            <div class='border-[#e6e7e9] border-[1px] rounded-[4px] p-[7px] text-[14px] text-[#3A4259] relative leading-[22px] w-[378px]'>
              <div>
                <span class='text-[#3487ff] text-[14px]'>{n.sku}</span>
                <el-divider direction='vertical' />
              </div>
              <p>自定义SKU：<span>{n.custom_sku || ''}</span></p>

              <el-tooltip popper-class="jsx-tab-tip" effect="dark" content={n.sku_cn_title} placement="top">
                <div class="overflow-line text-[#333333]">{n.sku_cn_title}</div>
              </el-tooltip>

              <p>退货数量：<span>{n.quantity || ''}</span></p>

              <div class='text-[#FF0000]'>退货原因：{n.problem_type_desc}</div>

              <div class='absolute right-[0] top-[0]'>
                <span class='leading-[17px] '>
                  {row.original_order_currency} {n.original_price}
                </span>
                <span class='bg-[#EBECEE] text-[#FF0000] rounded-bl-[4px] px-[4px] ml-[4px]'>
                  *{n.quantity}
                </span>
              </div>
            </div>
          ))}
        </div> -->
    </VTable>

    <Log dialog v-model="logVisible" :autoLoad="false" tag="exchange" :business_id="logId" />

    <AddReturn ref="AddReturnRef" v-model="visible" :id="returnId" :disabled="returnDisabled" @refresh="closeAddReturn" />
    <!-- <AddReturn v-model="addVisible" :id="returnId" @close="handleClose" :disabled="returnDisabled" @refresh="handleRefresh" /> -->

    <ApprovalDialog v-model="approvalVisible" :rows="rows" @refresh="handleRefresh" />
    <!-- 导出 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import WarehouseSelect from "@/components/WarehouseSelect/index.vue"
import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"

import ApprovalDialog from "@/views/user/list/detail/ReturnRecord/ApprovalDialog/index.vue"
import AddReturn from "./components/AddReturn/index.vue"
const AddReturnRef = ref()
import Log from "@/components/Log/index.vue"
const logVisible = ref(false)
const logId = ref("")
const handleLog = (item) => {
  logId.value = item.id
  logVisible.value = true
}

import ExpandList from "@/components/ExpandList/index.vue"
import { userAuthList } from "@/Auth/user.js"
import { isPermission } from "@/hooks/permission.js"
import { getExchangeList } from "./api/index"

const visible = ref(false)
const returnId = ref("")
const returnDisabled = ref(false)
// 编辑
const handleEdit = (type, item = {}) => {
  returnId.value = ""
  returnDisabled.value = false
  if (type == "edit") {
    returnId.value = item.id
  }
  if (type == "look") {
    returnId.value = item.id
    returnDisabled.value = true
  }
  visible.value = true
}
const closeAddReturn = () => {
  returnId.value = ""
  visible.value = false
  tableRef?.value.query()
}
const router = useRouter()
import { formOption, fieldList, tablecColumns } from "./config.jsx"
let stringKeys = []
stringKeys = fieldList.value.filter((v) => ["skuRange", "noRange", "orderRange"].includes(v.field)).map((v) => v.select)
stringKeys = stringKeys.flat().map((v) => v.value)
const tableRef = ref()
const formShow = ref(false)
onMounted(async () => {
  tableOptions.columns = [{ fixed: "left", type: "checkbox", width: 50 }]
  tableOptions.columns = tableOptions.columns.concat(tablecColumns.value)
  tableOptions.columns.push(handleColumn)
  rendererView()
  setTimeout(() => {
    initOrder()
    nextTick(() => {
      formShow.value = true
      tableRef?.value?.updateScroll()
      rendererView()
    })
  }, 100)
})
onActivated(() => {
  initOrder()
})
const initOrder = () => {
  const { form, id } = router.currentRoute.value.query
  if (form == "order" && id) {
    setTimeout(() => {
      visible.value = true
      AddReturnRef.value.noCombined = { type: "order_sn", value: id }
      AddReturnRef.value.handleGetOrderInfo()
    }, 500)
  }
}
const statusRadio = ref("")
const tab = ref([])
import { exchangeStatus } from "./api"
const getStatusTab = async (form = {}) => {
  try {
    // statusRadio.value = ""
    // console.log(form)
    const { data } = (await exchangeStatus({ ...form, exchange_status: "" })) || {}
    tab.value = data
  } catch (e) {
    console.error(e)
  }
}

const handleStatusChange = (tab, event) => {
  nextTick(() => {
    tableRef?.value.query()
  })
}
const getTotal = () => {
  return eval(tab.value.map((v) => v.quantity).join("+"))
}

// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let checkRow = tableRef?.value.$table.getCheckboxRecords()
  // console.log(listRef.value?.tableRef?.getCheckboxRecords());
  let condition = {}
  if (checkRow.length) {
    condition = { order_sn: checkRow.map((v) => v.order_sn) }
  } else {
    condition = tableRef?.value.getQueryForm()
    condition = initForm(condition)
  }
  // console.log(condition);
  // let condition = { ...formData.value }
  DerivedCenterRef.value.open({
    tag_name: e == 1 ? "return_goods_sku_export" : "return_goods_order_export",
    exportName: e == 1 ? "【订单退换货管理】退款SKU明细导出" : "【订单退换货管理】退款订单明细导出",
    condition,
  })
}

const getRows = (rows, expand) => {
  rows.expandStatus = expand
  const { products = [] } = rows || {}
  if (expand) return products
  if (!products?.length) return []
  if (products.length > 0 && products.length < 1) {
    return products
  }
  if (!expand) {
    return products?.slice(0, 1)
  }
}
const approvalVisible = ref(false)
const rows = ref([])
// 审核
const handleBatchApproval = () => {
  console.log(12)
  const select = tableRef?.value?.$table?.getCheckboxRecords()
  if (!select.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  rows.value = select
  approvalVisible.value = true
}

const handleApproval = (item) => {
  // returnId.value = item.id
  rows.value = [item]
  approvalVisible.value = true
}

const handleRefresh = () => {}

// 渲染表格列
const rendererView = (e) => {
  nextTick(() => {
    tableRef?.value?.$table.loadColumn(tableOptions.columns)
  })
}
const rowStyle = ({ row, column }) => {
  return { height: `${row.expandStatus ? row.products.length * 112 : 132}px` }
}
const tableOptions = reactive({
  formConfig: {
    // save: "/oms/user/refund", // 必填，唯一
    data: {
      storehouse: { type: "exchange_warehouse_id", value: "" },
      operator: { type: "create_user", value: "" },
      refund_status: "",
      skuRange: { type: "sku", value: "" },
      noRange: { type: "order_sn", value: "" },
      orderRange: { type: "exchange_tracking_number", value: "" },
      timeRange: { type: "apply_at", value: "" },
    },
  },
  showOverflow: "title",
  // showOverflow: false,
  cellStyle: rowStyle,
  columns: [
    // { fixed: "left", type: "checkbox", width: 50 },
    // {
    //   title: "操作",
    //   width: 100,
    //   fixed: "right",
    //   slots: {
    //     default: ({ row }) => {
    //       return (
    //         <div class="grid grid-cols-2 handle-btn">
    //           {isPermission([userAuthList.return.details]) && (
    //             <el-button link type="primary" onClick={() => handleEdit("look", row)}>
    //               详情
    //             </el-button>
    //           )}
    //           {[1, 3].includes(+row.exchange_status) && isPermission([userAuthList.return.edit]) && (
    //             <el-button link type="primary" onClick={() => handleEdit("edit", row)}>
    //               编辑{" "}
    //             </el-button>
    //           )}
    //           {[1, 3].includes(+row.exchange_status) && isPermission([userAuthList.return.audit]) && (
    //             <el-button link type="primary" onClick={() => handleApproval(row)}>
    //               审核
    //             </el-button>
    //           )}
    //           {isPermission([userAuthList.return.log]) && (
    //             <el-button link type="primary" onClick={() => handleLog(row)}>
    //               日志
    //             </el-button>
    //           )}
    //         </div>
    //       )
    //     },
    //   },
    // },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let param = { ...page, ...form, exchange_status: statusRadio.value }
        // param.platform_id = param.platform_id ? [param.platform_id] : []
        // stringKeys.forEach((key) => {
        //   if (param[key]) {
        //     param[key] = param[key]?.split?.("\n").filter(Boolean)
        //     param[key] = param[key]?.map((v) => v?.trim())
        //   }
        // })
        // getStatusTab(param)
        param = initForm(param)
        // statusRadio.value = ""
        // const { data } = (await exchangeStatus({ ...form, exchange_status: "" })) || {}
        tableRef?.value?.$table.reloadData([])
        return getExchangeList(param)
      },
    },
  },
})

const initForm = (form) => {
  stringKeys.forEach((key) => {
    if (form[key]) {
      form[key] = form[key]?.split?.("\n").filter(Boolean)
      form[key] = form[key]?.map((v) => v?.trim())
    }
  })
  getStatusTab(form)
  return form
}

const handleColumn = {
  title: "操作",
  width: 100,
  fixed: "right",
  slots: {
    default: ({ row }) => {
      return (
        <div class="grid grid-cols-2 handle-btn">
          {isPermission([userAuthList.return.details]) && (
            <el-button link type="primary" onClick={() => handleEdit("look", row)}>
              详情
            </el-button>
          )}

          {[1, 3].includes(+row.exchange_status) && isPermission([userAuthList.return.edit]) && (
            <el-button link type="primary" onClick={() => handleEdit("edit", row)}>
              编辑{" "}
            </el-button>
          )}
          {[1, 3].includes(+row.exchange_status) && isPermission([userAuthList.return.audit]) && (
            <el-button link type="primary" onClick={() => handleApproval(row)}>
              审核
            </el-button>
          )}

          {isPermission([userAuthList.return.log]) && (
            <el-button link type="primary" onClick={() => handleLog(row)}>
              日志
            </el-button>
          )}
        </div>
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.table-view {
  // background: #efefef;
  background: var(--base-paint);
  :deep(.vx-table__form-content) {
    border-radius: 6px;
    margin-bottom: 8px;
  }
  :deep(.vx-table__form) {
    .vx-table__form-content {
      border-radius: 8px;
      margin-bottom: 8px;
      background-image: none;
    }
  }
  :deep(.vx-table__content) {
    background: var(--vxe-table-body-background-color);
    border-radius: 8px 8px 0 0;
  }
}
:deep(.table-view) {
  .vxe-cell {
    max-height: 100% !important;
    overflow: visible !important;
  }
  .remark {
    width: 100%;
    white-space: pre-wrap;
    word-wrap: break-word;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .handle-btn {
    .el-button {
      margin-left: 0;
    }
  }
}
</style>
